﻿
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web;
using System.Web.Mvc;

using FlowerBLL;
using FlowerModel;

namespace FlowerManagement.Controllers
{
    public class HomeController : Controller
    {
        UsersBLL bll = new UsersBLL();
        FlowersBLL Fbll = new FlowersBLL();
        //
        // GET: /Home/

        #region 登录
        /// <summary>
        /// 创建登录视图
        /// </summary>
        /// <returns></returns>
        public ActionResult Login()
        {
            return View();
        }
        /// <summary>
        /// 实现登录
        /// </summary>
        /// <returns></returns>
        public int LoginDo()
        {
            var tel = Request["tel"];
            var pwd = Request["pwd"];
            var user = bll.Login<Users>(tel, pwd);

            if (Request["yzm"].ToString().ToUpper() == Session["CheckCode"].ToString().ToUpper())
            {
                if (user != null && user.Id != 0)
                {
                    Session["name"] = user.Name;
                    return 1;
                }
                else
                {
                    return 0;
                }
            }
            return 2;
        }
        
        #endregion
     
        #region 注册
        /// <summary>
        /// 创建注册视图
        /// </summary>
        /// <returns></returns>
        public ActionResult Register()
        {
            return View();
        }
        /// <summary>
        /// 实现注册功能
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public int RegisterDo(Users user)
        {
            user.Name = Request["name"];
            user.Phone = Request["tel"];
            user.Pwd = Request["pwd"];
            user.RegistTime = DateTime.Now;
            if (Request["yan"].ToString().ToUpper() == CookiesHelper.GetCookie("yan").ToUpper() && user.Phone==CookiesHelper.GetCookie("tel"))
            {
                if (bll.IsPhone<Users>(user.Phone)==1)
                {
                    return 3;
                }
                if (bll.Register<Users>(user)> 0)
                {
                    return 1;
                }
                else
                {
                    return 0;
                }
            }
            else
            {
                return 2;
            }
        }
        #endregion

        #region 获取手机验证码
        /// <summary>
        /// 生成6位数字验证码
        /// </summary>
        /// <returns></returns>
        public string YanZheng(string tel)
        {
            Random rd = new Random();
            int num = rd.Next(100000, 1000000);
            CookiesHelper.SetCookie("tel", tel, DateTime.Now.AddMinutes(30));
            CookiesHelper.SetCookie("yan", num.ToString(), DateTime.Now.AddMinutes(30));
            string json = Main(tel, num.ToString());
            return json;
        }
        /// <summary>
        /// 获取手机验证码
        /// </summary>
        private const String host = "http://sms.market.alicloudapi.com";
        private const String path = "/singleSendSms";
        private const String method = "GET";
        private const String appcode = "e58c2724f9024f86973095d27a0ee45b";
        static string Main(string tel, string num)
        {
            String querys = "ParamString={\"code\":\"" + num + "\"}&RecNum=" + tel + "&SignName=千百意花卉&TemplateCode=SMS_82090042";
            String bodys = "";
            String url = host + path;
            HttpWebRequest httpRequest = null;
            HttpWebResponse httpResponse = null;

            if (0 < querys.Length)
            {
                url = url + "?" + querys;
            }

            if (host.Contains("https://"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
            }
            else
            {
                httpRequest = (HttpWebRequest)WebRequest.Create(url);
            }
            httpRequest.Method = method;
            httpRequest.Headers.Add("Authorization", "APPCODE " + appcode);
            if (0 < bodys.Length)
            {
                byte[] data = Encoding.UTF8.GetBytes(bodys);
                using (Stream stream = httpRequest.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            try
            {
                httpResponse = (HttpWebResponse)httpRequest.GetResponse();
            }
            catch (WebException ex)
            {
                httpResponse = (HttpWebResponse)ex.Response;
            }

            Console.WriteLine(httpResponse.StatusCode);
            Console.WriteLine(httpResponse.Method);
            Console.WriteLine(httpResponse.Headers);
            Stream st = httpResponse.GetResponseStream();
            StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));
            string json = reader.ReadToEnd();
            return json;
        }

        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true;
        }

        #endregion

        /// <summary>
        /// 创建首页视图
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
      
            return View(Fbll.GetFlowers<Flowers>());
        }
       
        /// <summary>
        /// 购物车
        /// </summary>
        /// <returns></returns>
        public ActionResult IndexDo(int id)
        {
            var name=Session["name"];
             
            if(name==null)
            {
                return Content("<script>alert('请先登录!');location.href='/Home/Login';</script>");
            }
            else
            {
                if (Fbll.AddMyCar(id) > 0)
                {
                    return Content("<script>location.href='/Home/MyCar/?name="+name+"';</script>");
                }
                else
                {
                    return Content("<script>alert('加入购物车失败');location.href='/Home/Index';</script>");
                }
            }
            
        }
        /// <summary>
        /// 购物车显示
        /// </summary>
        /// <returns></returns>
        public ActionResult MyCar()
        {
            ViewBag.list = Fbll.MyCarList();
            return View();
        }
        /// <summary>
        /// 加
        /// </summary>
        /// <param name="buy"></param>
        /// <returns></returns>
        public int jia(MyCar my)
        {
            var id = Convert.ToInt32(Request["id"]);
            var num = Fbll.UpdateNum(id);

            my.Id = id;
            my.ByNum = num + 1;

            if (Fbll.UpdateKNum(my) > 0)
            {
                ViewBag.jia = my.ByNum;
                return 1;
            }
            else
            {
                return 0;
            }
        }
        /// <summary>
        /// 减
        /// </summary>
        /// <param name="buy"></param>
        /// <returns></returns>
        public int jian(MyCar my)
        {
            var id = Convert.ToInt32(Request["id"]);
            var num = Fbll.UpdateNum(id);

            if (num <= 0)
            {
                my.Id = id;
                my.ByNum = 0;
                if (Fbll.UpdateKNum(my) > 0)
                {
                    ViewBag.jian = my.ByNum;
                    return 1;
                }
                else
                {
                    return 0;
                }
            }
            else
            {
                my.Id = id;
                my.ByNum = num - 1;

                if (Fbll.UpdateKNum(my) > 0)
                {
                    ViewBag.jian = my.ByNum;
                    return 1;
                }
                else
                {
                    return 0;
                }
            }
        }
        /// <summary>
        /// 下单
        /// </summary>
        /// <returns></returns>
        public int AddOrder()
        {
            if(Request["id"].Length>0)
            {
                string result = Request["id"].Substring(0, Request["id"].Length - 1);

                string[] res = result.Split(',');

                foreach (var item in res)
                {
                    Fbll.AddOrder(Convert.ToInt32( item));
                }
                return 1;
            }
            else
            {
                return 0;
            }  
        }

        /// <summary>
        /// 删除购物车
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Delete(int id)
        {
            if(Fbll.Delete<Flowers>(id)==true)
            {
                return Content("<script>alert('删除成功');location.href='/Home/MyCar';</script>");
            }
            else
            {
                return Content("<script>alert('删除失败');location.href='/Home/MyCar';</script>");
            }
        }
    }
}
